<?php

namespace App\Models\Common;

use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class FsCompanyUserMappingModel extends BaseModel
{
    use KfUid;
    use KfSoftDeletes;

    protected $table = 'fs_company_user_mappings';

    protected $fillable = [
        'feishuId', // feishuId  和fs_company_users关联的字段。多对多 - 即将废弃
        'businessType', // 即将废弃
        'fsCompanyId',
        'rmsUserId', // 冗余辅助查询字段
    ];

    const BUSINESS_TYPE_ROOT         = 0;
    const BUSINESS_TYPE_CRUISE_CHECK = 1;

    const BUSINESS_TYPE_TEXT = [
        self::BUSINESS_TYPE_ROOT         => '', // 根目录
        self::BUSINESS_TYPE_CRUISE_CHECK => '品控', // 稽核
    ];

    /**
     * 用户的角色列表
     * @return HasMany
     */
    public function fsCompanyRoleMappingRel(): HasMany
    {
        return $this->hasMany(FsCompanyRoleMappingModel::class, 'fsCompanyUserMappingId', 'id');
    }

    public static function add(string $feishuId, int $fsCompanyId, int $businessType, int $rmsUserId)
    {
        return self::query()->updateOrCreate([
            'feishuId'     => $feishuId,
            'fsCompanyId'  => $fsCompanyId,
            'businessType' => $businessType
        ], ['rmsUserId' => $rmsUserId]);
    }
    /**
     * @return HasOne  FsCompanyUserModel
     */
    public function fsCompanyUserRel(): HasOne
    {
        return $this->hasOne(FsCompanyUserModel::class, 'feishuId', 'feishuId');
    }

    /**
     * 根据飞书id获取组织id
     * @param string $feishuId
     * @return int
     */
    public static function getOrganizationIdByFeiShuId(string $feishuId): int
    {
        $fsCompanyId = (int)self::query()->where('feishuId', $feishuId)->orderByDesc('id')->value('fsCompanyId');
        if (!$fsCompanyId) {
            return 0;
        }

        return (int)FsCompanyModel::query()->where('id', $fsCompanyId)->value('organizationId');
    }

    /**
     * 新版的获取行
     * @param int $fsCompanyId
     * @param int $rmsUserId
     */
    public static function getNewData(int $fsCompanyId, int $rmsUserId)
    {
        return self::query()
                   ->where('fsCompanyId', $fsCompanyId)
                   ->where('rmsUserId', $rmsUserId)
                   ->where('feishuId', '')
                   ->first();

    }
}
